//
//  BDBeidouViewController.m
//  BeidouMall
//
//  Created by qie on 16/3/29.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDBeidouViewController.h"
#import "BDNavigationController.h"
#import "BDBeidouHeaderView.h"
#import "BDGoodDetailViewController.h"
#import "BDBeidouPayViewController.h"
#import "BDPaySuccessViewController.h"

#define kPageSize 20

@interface BDBeidouViewController () <UITableViewDelegate,UITableViewDataSource,BDBeidouHeaderViewDelegate,UIActionSheetDelegate,UITextFieldDelegate>
{
    NSMutableArray *_beidouList;// 购物车原始数据
    NSMutableArray *_beidouGroupList;// 购物车分组之后的数据
    NSMutableArray *_storeList;// 存放商店id用于区分分组
    NSInteger _curPage;
    UITextField *_selectTextField;// 控制当前选择的textfield
    
    BOOL _hasConveniency;// 是否有便民控制全选按钮是否可以点击
    NSUInteger _noConveniencyCount;// 非便民商品的数量
    BOOL isPresentLoginView;// 第一次弹出登录框后用户取消后不让它继续弹出
    BOOL refreshDeleteView;// 指定行是否显示编辑样式
    NSInteger deleteSection;// 显示编辑样式的行号
    BOOL deleteMode;// 是否为可删除模式
    
    UIImageView *_navBarHairlineImageView;// 原生导航栏上的黑线,原来的自定义导航栏需要全透明所以原生的那条黑线需要隐藏，现在无所谓
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIImageView *bottomImageView;// 全选图片
@property (weak, nonatomic) IBOutlet UIButton *allSelectButton;// 全选按钮
@property (weak, nonatomic) IBOutlet UILabel *allLabel;// 全选label
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBottomSpace;// tableView离底部的距离

@property (weak, nonatomic) IBOutlet UILabel *totalLabel;// 合计
@property (weak, nonatomic) IBOutlet UIView *payView;// 隐藏后显示删除
@property (weak, nonatomic) IBOutlet UILabel *payLabel;// 去结算
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;
@property (weak, nonatomic) IBOutlet UIButton *editButton;// 顶部编辑button

@end

@implementation BDBeidouViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.editButton setTitle:NSLocalizedString(@"EditAll", nil) forState:UIControlStateNormal];
    [self.editButton setTitle:NSLocalizedString(@"Done", nil) forState:UIControlStateSelected];
    
    
    self.allLabel.text = NSLocalizedString(@"AllSelect", nil);
    [self.deleteButton setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        self.editButton.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:10.0];
        self.allLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
    }
    
    _beidouList = [NSMutableArray array];
    _storeList = [NSMutableArray array];
    _beidouGroupList = [NSMutableArray array];
    
    [self setTableViewHeader];
    
//    self.deleteButton.layer.cornerRadius = 2.0;
//    self.deleteButton.layer.borderWidth = 1.0;
//    self.deleteButton.layer.borderColor = [RGBColor(159, 27, 27) CGColor];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavgationBarBlackLine];
    // nav_bg2一个透明的图片替换原来的nav_bg
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg2"] forBarMetrics:UIBarMetricsDefault];
    [self dropShadowWithOffset:CGSizeMake(0, 0)
                        radius:2
                         color:[UIColor lightGrayColor]
                       opacity:0.8];
    
    if ([[BDAccountManagerModel shareInstance].payResult isEqualToString:@"selectTabBar"] ||
        [[BDAccountManagerModel shareInstance].payResult isEqualToString:@"popToRoot"]) {// 当支付完成(成功或失败)跳回到根页面后要选择到我的这一项
        [BDAccountManagerModel shareInstance].payResult = @"selectTabBar";
        self.tabBarController.selectedIndex = 4;
    } else {
        if ([[BDAccountManagerModel shareInstance].payResult isEqualToString:@"success"] ||
            [[BDAccountManagerModel shareInstance].payResult isEqualToString:@"fail"]) {// 支付成功或失败
            
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            BDNavigationController *nav_payVc = [stroyboard instantiateViewControllerWithIdentifier:@"PaySuccessStroyboardID"];
            BDPaySuccessViewController *payVc = (BDPaySuccessViewController *)nav_payVc.topViewController;
            payVc.type = [BDAccountManagerModel shareInstance].payResult;
            [self presentViewController:nav_payVc animated:YES completion:nil];
            
        } else if ([[BDAccountManagerModel shareInstance].payResult isEqualToString:@"popToRoot"]) {// 退到根节点
            [BDAccountManagerModel shareInstance].payResult = @"selectTabBar";
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else if (![BDAccountManagerModel shareInstance].login && !isPresentLoginView) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
            [self presentViewController:nav_addrVc animated:YES completion:nil];
            isPresentLoginView = YES;
        } else {
            [_tableView.mj_header beginRefreshing];
        }
    }
    // 标题国际化
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont fontWithName:@"BZDHT" size:12.0],
           NSForegroundColorAttributeName:RGBColor(51, 51, 51)}];
    } else {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0],
           NSForegroundColorAttributeName:RGBColor(51, 51, 51)}];
    }
    self.title = NSLocalizedString(@"beidou", nil);
    // 编辑全部恢复
    deleteSection = -1;
    deleteMode = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.editButton.selected = NO;
    self.totalLabel.hidden = NO;
    self.payView.hidden = NO;
    self.deleteButton.hidden = YES;
    
    [self.tableView setContentOffset:CGPointMake(0, 0)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private method

- (void)reloadData:(id) sender {
    _curPage = sender == self ? 1 : _curPage + 1;
    
    NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@&pageSize=%d&currentPage=%ld",
                     [BDNetworking shareInstance].baseUrl,
                     Cart,
                     [BDAccountManagerModel shareInstance].userId,
                     kPageSize,
                     (long)_curPage];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
            if ([_tableView.mj_footer isRefreshing]) {
                [_tableView.mj_footer endRefreshing];
            }
        });
        
        if (error != nil) {
            NSLog(@"获取背兜数据失败:%@",error);
            if ([[error localizedDescription] isEqualToString:@"登录超时"] && error.code == 401) {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Login timeout", nil)];
                // 清除webViw cookie
                NSHTTPCookie *cookie;
                NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                for (cookie in [storage cookies])
                {
                    [storage deleteCookie:cookie];
                }
                if (!isPresentLoginView) {
                    [BDAccountManagerModel shareInstance].authorization = @"";
                    [BDAccountManagerModel shareInstance].login = NO;
                    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                    BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
                    [self presentViewController:nav_addrVc animated:YES completion:nil];
                    isPresentLoginView = YES;
                }
            } else {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Failed to get data", nil)];
            }
        } else {
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                if ([resultList count] > 0) {
                    _tableView.mj_footer.hidden = [resultList count] == kPageSize ? NO : YES;
                    if (sender == self) {
                        [_beidouList removeAllObjects];
                        [_beidouGroupList removeAllObjects];
                        [_storeList removeAllObjects];
                    }
                    [_beidouList addObjectsFromArray:resultList];
                } else {
                    if (_curPage > 1) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    } else { // 刷新之前的数据应该清零
                        [_beidouList removeAllObjects];
                        [_beidouGroupList removeAllObjects];
                        [_storeList removeAllObjects];
                    }
                }
                [self dataProcessMethod];
            }
        }
    }];
}

- (void)setTableViewHeader {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:self];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = header;
}

- (void)dataProcessMethod {// 将原始数据按照店铺id分组,顺便计算是否有便民商品和非便民商品
    _noConveniencyCount = 0;
    _hasConveniency = NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou2"];
        self.allSelectButton.selected = NO;
        self.totalLabel.text = [NSString stringWithFormat:@"%@%.2f",NSLocalizedString(@"Total:", nil),0.0];
        self.payLabel.text = [NSString stringWithFormat:@"%@(%lu)",NSLocalizedString(@"Settlement", nil),(unsigned long)0];
    });
    
    for (NSDictionary *commDic in _beidouList) {// 将每种店铺id取出来放入数组中
        NSDictionary *commodityDic = commDic[@"commodity"];
        if (![commodityDic isEqual:[NSNull null]] &&
            [commodityDic isKindOfClass:[NSDictionary class]]) {
            NSDictionary *storeDic = commodityDic[@"store"];
            if (![storeDic isEqual:[NSNull null]] &&
                [storeDic isKindOfClass:[NSDictionary class]]) {
                NSString *storeId = storeDic[@"storeId"];
                if (![storeId isEqual:[NSNull null]]) {
                    int count = 0;
                    for (NSString *store_id in _storeList) {
                        if (![storeId isEqualToString:store_id]) {
                            count++;
                        }
                    }
                    if (_storeList.count == count) {
                        [_storeList addObject:storeId];
                    }
                }
            }
        }
    }
    
    [_beidouGroupList removeAllObjects];
    // 按照店铺id给商品分组放入小数组,每个店铺组成大数组
    for (int index = 0; index < _storeList.count; index++) {
        NSMutableArray *dataList = [NSMutableArray array];
        NSString *store_id = _storeList[index];
        for (NSMutableDictionary *commDic in _beidouList) {
            NSDictionary *commodityDic = commDic[@"commodity"];
            if (![commodityDic isEqual:[NSNull null]] &&
                [commodityDic isKindOfClass:[NSDictionary class]]) {
                NSDictionary *storeDic = commodityDic[@"store"];
                if (![storeDic isEqual:[NSNull null]] &&
                    [storeDic isKindOfClass:[NSDictionary class]]) {
                    NSString *storeId = storeDic[@"storeId"];
                    if ([storeId isEqualToString:store_id]) {
                        [commDic setValue:@"no" forKeyPath:@"wyselected"];
                        [dataList addObject:commDic];
                    }
                }
            }
        }
        [_beidouGroupList addObject:dataList];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)deleteGood {// 删除购物车里面的商品
    // add by wyp 2016-07-14 新的编辑单个店铺商品参数需要重置
    refreshDeleteView = NO;
    deleteSection = -1;
    
    NSMutableArray *deleList = [NSMutableArray array];
    for (NSArray *innerList in _beidouGroupList) {// 删除被选中的商品
        for (NSDictionary *comDic in innerList) {
            NSString *wySelected = [comDic valueForKey:@"wyselected"];
            if (wySelected.length > 0 && [wySelected isEqualToString:@"yes"]) {
                NSString *comID = comDic[@"commodity"][@"commodityId"];
                if (![comID isEqual:[NSNull null]] && comID.length > 0) {
                    [deleList addObject:comID];
                }
            }
        }
    }
    if (deleList.count == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"please select the goods to be deleted", nil)];
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
//        NSDictionary *parameters = @{@"userId":[BDAccountManagerModel shareInstance].userId,
//                                     @"commodityIds":deleList};
        NSString *deleStr = [deleList componentsJoinedByString:@","];
        
        NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@&commodityIds=%@",
                         [BDNetworking shareInstance].baseUrl,
                         Cart,
                         [BDAccountManagerModel shareInstance].userId,
                         deleStr];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"DELETE" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"删除购物车商品失败:%@",error);
                hud.labelText = NSLocalizedString(@"delete goods failed", nil);
                [hud hideAfterDelay:0.5];
            } else {
                [hud hideAfterDelay:0.5];
                NSLog(@"result = %@",results);
                self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou2"];
                [self reloadData:self];
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 删除成功后顶部按钮变为编辑全部
                    self.editButton.selected = NO;
                });
            }
        }];
    }
}

- (void)calculateTotalPrice {// 计算选择的商品的总价格
    CGFloat totalPrice = 0.0;
    NSUInteger totalNum = 0;
    NSUInteger count = 0;
    for (NSArray *innerList in _beidouGroupList) {// 被选中的商品
        for (NSDictionary *comDic in innerList) {
            NSString *wySelected = [comDic valueForKey:@"wyselected"];
            if (wySelected.length > 0 && [wySelected isEqualToString:@"yes"]) {
                count++;
                NSString *goodDiscount = comDic[@"commodity"][@"commodityPrice"][@"discount"];
                NSString *goodPrice = comDic[@"commodity"][@"commodityPrice"][@"price"];
                if (![goodDiscount isEqual:[NSNull null]] &&
                    ![goodPrice isEqual:[NSNull null]]) {
                    // 折扣价格
                    CGFloat discount = [goodDiscount floatValue];
                    CGFloat price = [goodPrice floatValue];
                    CGFloat actualPrice = discount * price;
                    
                    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                    [numberFormatter setPositiveFormat:@"0.00"];
                    NSString *temp = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:actualPrice]];
                    // 精确到小数点后两位再计算
                    NSNumber *num = comDic[@"num"];
                    totalPrice += [num integerValue] * [temp floatValue];
                    totalNum += [num integerValue];
                }
            }
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.totalLabel.text = [NSString stringWithFormat:@"%@%.2f",NSLocalizedString(@"Total:", nil),totalPrice];
        self.payLabel.text = [NSString stringWithFormat:@"%@(%lu)",NSLocalizedString(@"Settlement", nil),(unsigned long)count];
    });
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        _navBarHairlineImageView = imageView2;
                        _navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)dropShadowWithOffset:(CGSize)offset
                      radius:(CGFloat)radius
                       color:(UIColor *)color
                     opacity:(CGFloat)opacity {
    
    // Creating shadow path for better performance
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.navigationController.navigationBar.bounds);
    self.navigationController.navigationBar.layer.shadowPath = path;
    CGPathCloseSubpath(path);
    CGPathRelease(path);
    
    self.navigationController.navigationBar.layer.shadowColor = color.CGColor;
    self.navigationController.navigationBar.layer.shadowOffset = offset;
    self.navigationController.navigationBar.layer.shadowRadius = radius;
    self.navigationController.navigationBar.layer.shadowOpacity = opacity;
    
    // Default clipsToBounds is YES, will clip off the shadow, so we disable it.
    self.navigationController.navigationBar.clipsToBounds = NO;
    
}

#pragma mark tableView delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_beidouGroupList.count == 0) {
        self.editButton.hidden = YES;
        self.tableViewBottomSpace.constant = 49.0;
        self.bottomView.hidden = YES;
    } else {
        self.editButton.hidden = NO;
        self.tableViewBottomSpace.constant = 89.0;
        self.bottomView.hidden = NO;
    }
    return _beidouGroupList.count > 0 ? _beidouGroupList.count : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_beidouGroupList.count > 0) {
        NSArray *arr = _beidouGroupList[section];
        return arr.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_beidouGroupList.count > 0) {
        static NSString *cellStr = @"BeidouCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *arr = _beidouGroupList[indexPath.section];
            NSDictionary *commDic = arr[indexPath.row][@"commodity"];
            
            // 勾选按钮
            UIButton *button = (UIButton *)[cell viewWithTag:1001];
            // 商品选择图片
            NSString *select = arr[indexPath.row][@"wyselected"];
            UIImageView *selectImageView = (UIImageView *)[cell viewWithTag:101];
            if ([select isEqualToString:@"no"]) {
                selectImageView.image = [UIImage imageNamed:@"beidou_gou2"];
                button.selected = NO;
            } else if ([select isEqualToString:@"yes"]) {
                selectImageView.image = [UIImage imageNamed:@"beidou_gou"];
                button.selected = YES;
            }
            
            // 商品图片
            NSString *storeImageUrl = commDic[@"icon"];
            UIImageView *storeImageView = (UIImageView *)[cell viewWithTag:102];
            if (![storeImageUrl isEqual:[NSNull null]]) {
                NSInteger width = storeImageView.width * 2;
                NSInteger height = storeImageView.height * 2;
                storeImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",storeImageUrl,(long)width,(long)height];
                [storeImageView sd_setImageWithURL:[NSURL URLWithString:storeImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"]];
            }
            
            
            UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:103];
            NSString *goodName = commDic[@"name"];
            if (![goodName isEqual:[NSNull null]]) {
                goodNameLabel.text = goodName;
            }
            // 商品库存
            UILabel *numLabel = (UILabel *)[cell viewWithTag:104];
            NSString *num = commDic[@"num"];
            if (![num isEqual:[NSNull null]]) {
                numLabel.text = [NSString stringWithFormat:@"%@%ld",NSLocalizedString(@"Stock", nil),(long)[num integerValue]];
                if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                    numLabel.text = [NSString stringWithFormat:@"%@%ld",@"库存：",(long)[num integerValue]];
                }
            }
            
            UILabel *bianminLabel = (UILabel *)[cell viewWithTag:205];
            bianminLabel.layer.borderWidth = 1.0;
            bianminLabel.layer.cornerRadius = 2.0;
            bianminLabel.layer.borderColor = [RGBColor(215, 19, 33) CGColor];
            bianminLabel.hidden = YES;
            NSDictionary *classify = commDic[@"classify"];
            if (![classify isEqual:[NSNull null]] &&
                [classify isKindOfClass:[NSDictionary class]]) {
                NSString *firstLevel = classify[@"firstLevel"];
                if (![firstLevel isEqual:[NSNull null]]) {
                    if ([firstLevel isEqualToString:@"conveniency"]) {
                        _hasConveniency = YES;
                        bianminLabel.hidden = NO;
                    } else {
                        _noConveniencyCount++;
                    }
                }
            }
            
            // 商品折扣价格
            UILabel *goodDiscountLabel = (UILabel *)[cell viewWithTag:106];
            // 商品价格
            UILabel *goodPriceLabel = (UILabel *)[cell viewWithTag:107];
            
            NSString *goodDiscount = commDic[@"commodityPrice"][@"discount"];
            NSString *goodPrice = commDic[@"commodityPrice"][@"price"];
            if (![goodDiscount isEqual:[NSNull null]] &&
                ![goodPrice isEqual:[NSNull null]]) {
                // 折扣价格
                CGFloat discount = [goodDiscount floatValue];
                CGFloat price = [goodPrice floatValue];
                goodDiscountLabel.text = [NSString stringWithFormat:@"¥ %.2f",price * discount];
//                // 价格
//                NSString *str = [NSString stringWithFormat:@"¥ %.2f",[goodPrice floatValue]];
//                NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
//                NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attribtDic];
//                goodPriceLabel.attributedText = attribtStr;
//                if (discount >= 1.0 || [goodPriceLabel.text isEqualToString:goodDiscountLabel.text]) {
//                    goodPriceLabel.hidden = YES;
//                } else {
//                    goodPriceLabel.hidden = NO;
//                }
            }
            // 选择商品数量
            UIView *containerView = [cell viewWithTag:108];
//            containerView.layer.borderWidth = 0.6;
//            containerView.layer.cornerRadius = 3.0;
//            containerView.layer.borderColor = [RGBColor(54, 54, 54) CGColor];
            UITextField *textField = (UITextField *)[containerView viewWithTag:202];
            UIButton *addButton = (UIButton *)[containerView viewWithTag:203];
            addButton.layer.borderWidth = 0.6;
            addButton.layer.borderColor = [RGBColor(210, 210, 210) CGColor];
            
            NSString *goodNum = arr[indexPath.row][@"num"];
            if (![goodNum isEqual:[NSNull null]]) {
                textField.text = [NSString stringWithFormat:@"%@",goodNum];
                goodPriceLabel.text = [NSString stringWithFormat:@"X%@",goodNum];
                
                UIView *keyBoardTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
                keyBoardTopView.backgroundColor = [UIColor lightGrayColor];
                UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(12, 4, 60, 36)];
                [btn setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(onKeyBoardCancel:) forControlEvents:UIControlEventTouchUpInside];
                if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                    btn.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                }
                [keyBoardTopView addSubview:btn];
                
                UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(keyBoardTopView.bounds.size.width - 60 - 12, 4, 60, 36)];
                [btn2 setTitle:NSLocalizedString(@"Done", nil) forState:UIControlStateNormal];
                [btn2 setTitleColor:RGBColor(159, 27, 27) forState:UIControlStateNormal];
                [btn2 addTarget:self action:@selector(onKeyBoardFinsh:) forControlEvents:UIControlEventTouchUpInside];
                
                [keyBoardTopView addSubview:btn2];
                if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                    btn2.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                }
                textField.inputAccessoryView = keyBoardTopView;
                textField.layer.borderWidth = 0.6;
                textField.layer.borderColor = [RGBColor(210, 210, 210) CGColor];
                
                NSUInteger goodNumber = [goodNum integerValue];
                UIButton *button = (UIButton *)[containerView viewWithTag:201];
                button.enabled = goodNumber <= 1 ? NO : YES;
            }
            if (refreshDeleteView && indexPath.section == deleteSection) {
                for (UIView *view in cell.contentView.subviews) {
                    if (view.tag < 108 && view.tag > 102) {
                        view.hidden = YES;
                    }
                    if (view.tag == 205) {// 将便民标签从105改为205
                        view.hidden = YES;
                    }
                }
                
                containerView.hidden = NO;
                [cell viewWithTag:109].hidden = NO;
            } else if (refreshDeleteView && deleteSection == 10240) { 
                for (UIView *view in cell.contentView.subviews) {
                    if (view.tag < 108 && view.tag > 102) {
                        view.hidden = YES;
                    }
                    if (view.tag == 205) {
                        view.hidden = YES;
                    }
                }
                
                containerView.hidden = NO;
                [cell viewWithTag:109].hidden = YES;
                 
                for (NSLayoutConstraint *constaint in cell.contentView.constraints) {
                    if ([constaint.identifier isEqualToString:@"caclateViewLeading"]) {
                        constaint.constant = 40.0;
                    }
                    if ([constaint.identifier isEqualToString:@"caclateViewTrail"]) {
                        constaint.constant = 50.0;
                    }
                }
                
            } else {
                for (UIView *view in cell.contentView.subviews) {
                    if (view.tag < 108 && view.tag > 102) {
                        view.hidden = NO;
                    }
                }
                
                containerView.hidden = YES;
                [cell viewWithTag:109].hidden = YES;
                
                for (NSLayoutConstraint *constaint in cell.contentView.constraints) {
                    if ([constaint.identifier isEqualToString:@"caclateViewTrail"]) {
                        constaint.constant = 75.0;
                    }
                }
                
            }
            
            
        });
        return cell;
    } else {
        static NSString *cellStr = @"noCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    _tableView.scrollEnabled = _beidouGroupList.count > 0 ? YES : NO;
    return _beidouGroupList.count > 0 ? 107.0 : kScreen_Height - 104;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _beidouGroupList.count > 0 ? 40.0 : 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (_beidouGroupList.count > 0) {
        BDBeidouHeaderView *header = (BDBeidouHeaderView *)[[[NSBundle mainBundle] loadNibNamed:@"BDBeidouHeaderView" owner:nil options:nil] lastObject];
        header.tag = 900 + section;
        header.delegate = self;
        
        // 店铺名称
        UILabel *nameLabel = (UILabel *)[header viewWithTag:101];
        NSArray *arr = _beidouGroupList[section];
        NSString *storeName = arr[0][@"commodity"][@"store"][@"name"];
        if (![storeName isEqual:[NSNull null]] &&
            storeName.length > 0) {
            nameLabel.text = storeName;
        }
        // 勾选图片
        int count = 0;
        for (NSDictionary *comDic in arr) {
            NSString *select = [comDic valueForKey:@"wyselected"];
            if (select.length > 0 && [select isEqualToString:@"yes"]) {
                count++;
            }
        }
        UIImageView *imageView = [(UIImageView *)header viewWithTag:102];
        NSString *imageName = count == arr.count ? @"beidou_gou" : @"beidou_gou2";
        imageView.image = [UIImage imageNamed:imageName];
        // 勾选按钮
        UIButton *button = (UIButton *)[header viewWithTag:103];
        button.selected = count == arr.count ? YES : NO;
        
        // 编辑按钮
        UIButton *button2 = (UIButton *)[header viewWithTag:104];
        // 编辑label
        UILabel *editLabel = (UILabel *)[header viewWithTag:105];
        if (deleteSection == 10240) {
            button2.hidden = YES;
            editLabel.hidden = YES;
        } else {
            button2.hidden = NO;
            editLabel.hidden = NO;
            button2.selected = refreshDeleteView && section == deleteSection ? YES : NO;
            editLabel.text = refreshDeleteView && section == deleteSection ? NSLocalizedString(@"Done", nil) : NSLocalizedString(@"Edit", nil);
        }
        
        return header;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_beidouGroupList.count > 0) {
        NSDictionary *goodDic = _beidouGroupList[indexPath.section][indexPath.row];
        NSString *commodityId = goodDic[@"commodity"][@"commodityId"];
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
        BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
        detailVC.commodityId = commodityId;
        detailVC.isFromHomePage = NO;
        detailVC.notCustomNavigatonBar = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - UIScrollView delegate

//去掉UItableview headerview黏性
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        CGFloat sectionHeaderHeight = 40.0;
        if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

#pragma mark - BDBeidouHeaderViewDelegate

- (void)imageViewChangeMethod:(UIButton *)sender {// 勾选按钮
    BOOL conveniency = NO;
    int noConveniencyCount = 0;
    if ([sender.superview isKindOfClass:[BDBeidouHeaderView class]]) {
        UIView *superView = sender.superview;
        NSUInteger section = superView.tag - 900;
        NSArray *arr = _beidouGroupList[section];
        for (NSDictionary *comDic in arr) {// 先看自己店铺有没有 便民与非便民都有
            NSString *firstLevel = comDic[@"commodity"][@"classify"][@"firstLevel"];
            if ([firstLevel isEqualToString:@"conveniency"]) {
                conveniency = YES;
            } else {
                noConveniencyCount++;
            }
        }
    }
    for (NSArray *arr in _beidouGroupList) {
        for (NSDictionary *comDic in arr) {
            NSString *firstLevel = comDic[@"commodity"][@"classify"][@"firstLevel"];
            NSString *selected = comDic[@"wyselected"];
            if ([selected isEqualToString:@"yes"]) {// 再看已选择里面有没有 便民与非便民都有
                if ([firstLevel isEqualToString:@"conveniency"]) {
                    conveniency = YES;
                } else {
                    noConveniencyCount++;
                }
            }
        }
    }
    
    if (![[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"yes"]  && !deleteMode) {
        if (conveniency == YES) {// 不在指定地区,选择了便民商品
            [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can only be purchased in the designated area", nil) withOffsetY:0.0];
            return;
        }
    }
    
    if ((conveniency == YES && noConveniencyCount == 0) ||
        (conveniency == NO && noConveniencyCount > 0) ||
        deleteMode == YES) {// 全为便民或全为非便民
        sender.selected = !sender.selected;
        
        NSString *select = sender.selected ? @"yes" : @"no";
        if ([sender.superview isKindOfClass:[BDBeidouHeaderView class]]) {
            UIView *superView = sender.superview;
            NSUInteger section = superView.tag - 900;
            NSArray *arr = _beidouGroupList[section];
            for (NSDictionary *comDic in arr) {
                [comDic setValue:select forKeyPath:@"wyselected"];
            }
            
            // 处理底部全选按钮 如果所有商品都有被标记 全选按钮被点击
            BOOL allSelected = YES;
            for (NSArray *innerList in _beidouGroupList) {
                for (NSDictionary *comDic in innerList) {
                    if (![[comDic valueForKey:@"wyselected"] isEqualToString:@"yes"]) {
                        allSelected = NO;
                        break;
                    };
                }
            }
            if (allSelected) {// 相当于点击了底部全选按钮
                if ((_hasConveniency == YES && _noConveniencyCount == 0) ||
                    (_hasConveniency == NO && _noConveniencyCount > 0) ||
                    deleteMode == YES) {// 全为便民或全为非便民
                    self.allSelectButton.selected = YES;
                    self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou"];
                } else {
                    [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can’t be selected with other goods at the same time", nil) withOffsetY:0.0];
                    for (NSDictionary *comDic in arr) {
                        [comDic setValue:@"no" forKeyPath:@"wyselected"];
                    }
                }
            } else {
                self.allSelectButton.selected = NO;
                self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou2"];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            [self calculateTotalPrice];
        }
    } else {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can’t be selected with other goods at the same time", nil) withOffsetY:0.0];
    }
}

- (void)shopButtonMethod:(UIButton *)sender {
    
}

- (void)editButtonMethod:(UIButton *)sender {
    UIView *superView = sender.superview;
    NSUInteger section = superView.tag - 900;
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:section];
    refreshDeleteView = sender.selected ? YES : NO;
    deleteSection = sender.selected ? section : -1;
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - UITextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSString *repertory = _beidouGroupList[indexPath.section][indexPath.row][@"commodity"][@"num"];
    NSInteger repertoryNum = [repertory integerValue];
    
    NSString *futrueString = [textField.text changeCharactersInRange:range replacementString:string];
    if ([futrueString integerValue] > repertoryNum || repertoryNum == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Number is greater than the stock", nil) withOffsetY:-50];
        return NO;
    }
    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _selectTextField = textField;
    //  解决键盘挡住tableView问题
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= kScreen_Width - 216) {
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
        [_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // 恢复键盘多出的高度
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
}

- (void)onKeyBoardCancel:(UIButton *) sender {
    if ([_selectTextField isFirstResponder]) {
        [_selectTextField resignFirstResponder];
    }
    UIView *container = _selectTextField.superview;
    UIView *superView = container.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSNumber *num = _beidouGroupList[indexPath.section][indexPath.row][@"num"];
    _selectTextField.text = [NSString stringWithFormat:@"%ld",(long)[num integerValue]];
//    [self.tableView endEditing:YES];
}

- (void)onKeyBoardFinsh:(UIButton *) sender {
    sender.tag = 9527;
    [self cartEdit:sender];
}

// 修改购物车商品数量
- (void)cartEdit:(UIButton *) sender{
    UITableViewCell *cell;
    NSIndexPath *indexPath;
    NSUInteger num;
    if (sender.tag == 9527) {// textfield引起的修改
        UIView *container = _selectTextField.superview;
        UIView *superView = container.superview;
        while (![superView isKindOfClass:[UITableViewCell class]]) {
            superView = superView.superview;
        }
        cell = (UITableViewCell *)superView;
        indexPath = [self.tableView indexPathForCell:cell];
        num = [_selectTextField.text integerValue];
    } else {
        UIView *container = sender.superview;
        UIView *superView = container.superview;
        while (![superView isKindOfClass:[UITableViewCell class]]) {
            superView = superView.superview;
        }
        cell = (UITableViewCell *)superView;
        indexPath = [self.tableView indexPathForCell:cell];
        UITextField *textField = (UITextField *)[container viewWithTag:202];
        num = [textField.text integerValue];
    }
    
    NSDictionary *comDic = _beidouGroupList[indexPath.section][indexPath.row][@"commodity"];
    NSString *commodityId = comDic[@"commodityId"];
    if (num == 0) {
//        UIActionSheet *actionSheet = [[UIActionSheet alloc]
//                                      initWithTitle:NSLocalizedString(@"confirm delete this good?", nil)
//                                      delegate:self
//                                      cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
//                                      destructiveButtonTitle:NSLocalizedString(@"Confirm", nil)
//                                      otherButtonTitles:nil,nil];
//        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
//        [actionSheet showInView:self.view];

        JTSActionSheetTheme *theme = [JTSActionSheetTheme defaultTheme];
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
            theme.titleFont = [UIFont fontWithName:@"Bzdbt" size:15.0];
            theme.normalButtonFont = [UIFont fontWithName:@"Bzdbt" size:15.0];
            theme.boldButtonFont = [UIFont fontWithName:@"Bzdbt" size:15.0];
        }
        
        JTSActionSheetItem *confirm = [JTSActionSheetItem itemWithTitle:NSLocalizedString(@"Confirm", nil) action:^{
            UIView *container = _selectTextField.superview;
            UIView *superView = container.superview;
            while (![superView isKindOfClass:[UITableViewCell class]]) {
                superView = superView.superview;
            }
            UITableViewCell *cell = (UITableViewCell *)superView;
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            NSDictionary *comDic = _beidouGroupList[indexPath.section][indexPath.row];
            [comDic setValue:@"yes" forKey:@"wyselected"];
            
            [self deleteGood];
        } isDestructive:YES];
        JTSActionSheetItem *cancel = [JTSActionSheetItem itemWithTitle:NSLocalizedString(@"Cancel", nil) action:^{
            UIView *container = _selectTextField.superview;
            UIView *superView = container.superview;
            while (![superView isKindOfClass:[UITableViewCell class]]) {
                superView = superView.superview;
            }
            UITableViewCell *cell = (UITableViewCell *)superView;
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            
            NSNumber *backNum = _beidouGroupList[indexPath.section][indexPath.row][@"num"];
            _selectTextField.text = [NSString stringWithFormat:@"%@",backNum];
        } isDestructive:NO];
        
        JTSActionSheet *sheet = [[JTSActionSheet alloc] initWithTheme:theme
                                                                title:NSLocalizedString(@"confirm delete this good?", nil)
                                                          actionItems:@[confirm]
                                                           cancelItem:cancel];
        [sheet showInView:self.view];
        [_selectTextField resignFirstResponder];
        
        return;
    }
    if (![commodityId isEqual:[NSNull null]]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
        
        NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@&commodityId=%@&num=%@",
                         [BDNetworking shareInstance].baseUrl,
                         CartEdit,
                         [BDAccountManagerModel shareInstance].userId,
                         commodityId,
                         @(num)];
        
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"修改购物车失败:%@",error);
                hud.labelText = [error localizedDescription];
                [hud hideAfterDelay:0.5];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            } else {
                NSLog(@"results = %@",results);
                [hud hideAfterDelay:0.5];
                
                NSMutableDictionary *dic = _beidouGroupList[indexPath.section][indexPath.row];
                NSString *goodNumStr = [NSString stringWithFormat:@"%lu",(unsigned long)num];
                [dic setValue:goodNumStr forKey:@"num"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
                [self calculateTotalPrice];
            }
        }];
    }
}

#pragma mark - IBActions
// 顶部编辑按钮
- (IBAction)editButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        self.totalLabel.hidden = YES;
        self.payView.hidden = YES;
        self.deleteButton.hidden = NO;
        refreshDeleteView = YES;
        deleteSection = 10240;
        deleteMode = YES;
    } else {
        self.totalLabel.hidden = NO;
        self.payView.hidden = NO;
        self.deleteButton.hidden = YES;
        refreshDeleteView = NO;
        deleteSection = -1;
        deleteMode = NO;
    }
    
    // 模式切换时，删除之前选择的所有东西
    for (NSArray *innerList in _beidouGroupList) {
        for (NSDictionary *comDic in innerList) {
            [comDic setValue:@"no" forKeyPath:@"wyselected"];
        }
    }
    self.allSelectButton.selected = NO;
    self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou2"];
    [self calculateTotalPrice];
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (IBAction)payButtonPressed:(UIButton *)sender {
    NSMutableArray *payList = [NSMutableArray array];
    BOOL flag = NO;
    for (NSArray *innerList in _beidouGroupList) {
        NSMutableArray *payInnerList = [NSMutableArray array];
        for (NSDictionary *comDic in innerList) {
            if ([[comDic valueForKey:@"wyselected"] isEqualToString:@"yes"]) {
                // 非便民地区 购物车中便民商品可以删除，但是不可支付
                NSString *firstLevel = comDic[@"commodity"][@"classify"][@"firstLevel"];
                if ([firstLevel isEqualToString:@"conveniency"]) {
                    flag = YES;
                    if ([[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"no"]) {
                        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can only be purchased in the designated area", nil) withOffsetY:0.0];
                        return;
                    }
                }
                
                NSString *storeName = comDic[@"commodity"][@"store"][@"name"];
                NSString *storeId = comDic[@"commodity"][@"store"][@"storeId"];
                NSString *icon = comDic[@"commodity"][@"icon"];
                NSString *name = comDic[@"commodity"][@"name"];
                NSString *commodityId = comDic[@"commodity"][@"commodityId"];
                
                NSNumber *num = comDic[@"num"];
                NSString *goodDiscount = comDic[@"commodity"][@"commodityPrice"][@"discount"];
                NSString *goodPrice = comDic[@"commodity"][@"commodityPrice"][@"price"];
                CGFloat discount = [goodDiscount floatValue];
                CGFloat price = [goodPrice floatValue];
                CGFloat actualPrice = discount * price;
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                [numberFormatter setPositiveFormat:@"0.00"];
                NSString *temp = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:actualPrice]];
                CGFloat totalPrice = [temp floatValue];
                
                
                NSDictionary *dic = @{@"commodityId" : commodityId,
                                      @"num" : num,
                                      @"storeName" : storeName,
                                      @"storeId" : storeId,
                                      @"couponId" : [NSNull null],
                                      @"icon" : icon,
                                      @"name" : name,
                                      @"price" : @(totalPrice)};
                
                NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                
                [payInnerList addObject:resultDic];
            }
        }
        if (payInnerList.count > 0) {
            [payList addObject:payInnerList];
        }
    }
    if (payList.count > 0) {
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
        BDNavigationController *nav_vc = [stroyboard instantiateViewControllerWithIdentifier:@"navPayStoryboardID"];
        BDBeidouPayViewController *vc = (BDBeidouPayViewController *)nav_vc.topViewController;
        vc.payList = payList;
        vc.isConveniency = flag;
        vc.isFromShopCart = YES;// 如果是从购物车来的就清空购物车
        [self presentViewController:nav_vc animated:YES completion:nil];
    } else {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"did not select any goods", nil)];
    }
}


- (IBAction)deleteButtonPressed:(UIButton *)sender {
    [self deleteGood];
}

- (IBAction)deleteShopGoodButtonPressed:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSDictionary *comDic = _beidouGroupList[indexPath.section][indexPath.row];
    NSString *commodityId = comDic[@"commodity"][@"commodityId"];
    
    // add by wyp 2016-07-14 新的编辑单个店铺商品参数需要重置
    refreshDeleteView = NO;
    deleteSection = -1;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
    
    NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@&commodityIds=%@",
                     [BDNetworking shareInstance].baseUrl,
                     Cart,
                     [BDAccountManagerModel shareInstance].userId,
                     commodityId];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"DELETE" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"删除购物车商品失败:%@",error);
            hud.labelText = NSLocalizedString(@"delete goods failed", nil);
            [hud hideAfterDelay:0.5];
        } else {
            [hud hideAfterDelay:0.5];
            NSLog(@"result = %@",results);
//            self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou2"];
            [self reloadData:self];
        }
    }];
}


// cell勾选按钮
- (IBAction)cellButtonPressed:(UIButton *)sender {
    BOOL conveniency = NO;
    int noConveniencyCount = 0;
    for (NSArray *arr in _beidouGroupList) {
        for (NSDictionary *comDic in arr) {
            NSString *firstLevel = comDic[@"commodity"][@"classify"][@"firstLevel"];
            NSString *selected = comDic[@"wyselected"];
            if ([selected isEqualToString:@"yes"]) {// 从已选择里面判断
                if ([firstLevel isEqualToString:@"conveniency"]) {
                   conveniency = YES;
                } else {
                    noConveniencyCount++;
                }
            }
        }
    }
    
    BOOL canSelected = NO;
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSDictionary *comDic = _beidouGroupList[indexPath.section][indexPath.row];
    NSString *firstLevel = comDic[@"commodity"][@"classify"][@"firstLevel"];
    
    if (![[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"yes"] && !deleteMode) {
        if ([firstLevel isEqualToString:@"conveniency"]) {// 不在指定地区,选择了便民商品
            [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can only be purchased in the designated area", nil) withOffsetY:0.0];
            return;
        }
    }
    
    if ([firstLevel isEqualToString:@"conveniency"]) {// 当前选择的是便民商品
        if (noConveniencyCount == 0) {// 已选择里面没有非便民商品
            canSelected = YES;
        }
    } else {// 当前选择的是非便民商品
        if (!conveniency) {// 已选择里面没有便民商品
            canSelected = YES;
        }
    }
    
    if (deleteMode) {// 删除模式无视任何条件
        canSelected = YES;
    }
    
    if (canSelected) {
        sender.selected = !sender.selected;
        UIImageView *imageView = (UIImageView *)[cell viewWithTag:101];
        imageView.image = sender.selected ? [UIImage imageNamed:@"beidou_gou"] : [UIImage imageNamed:@"beidou_gou2"];
        NSString *select = sender.selected ? @"yes" : @"no";
        [comDic setValue:select forKeyPath:@"wyselected"];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
        // 处理底部全选按钮
        BOOL allSelected = YES;
        for (NSArray *innerList in _beidouGroupList) {
            for (NSDictionary *comDic in innerList) {
                if (![[comDic valueForKey:@"wyselected"] isEqualToString:@"yes"]) {
                    allSelected = NO;
                    break;
                };
            }
        }
        if (allSelected) {
            self.allSelectButton.selected = YES;
            self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou"];
        } else {
            self.allSelectButton.selected = NO;
            self.bottomImageView.image = [UIImage imageNamed:@"beidou_gou2"];
        }
        [self calculateTotalPrice];
    } else {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can’t be selected with other goods at the same time", nil) withOffsetY:0.0];
    }
    
}

- (IBAction)reduceButtonPressed:(UIButton *)sender {
    UIView *containerView = sender.superview;
    UITextField *textField = (UITextField *)[containerView viewWithTag:202];
    NSUInteger num = [textField.text integerValue];
    num--;
    textField.text = [NSString stringWithFormat:@"%lu",(unsigned long)num];
    if (num <= 1) {
        sender.enabled = NO;
    }
    [self cartEdit:sender];
}

- (IBAction)addButtonPressed:(UIButton *)sender {
    UIView *containerView = sender.superview;
    
    UITextField *textField = (UITextField *)[containerView viewWithTag:202];
    UIButton *button = (UIButton *)[containerView viewWithTag:201];
    NSUInteger num = [textField.text integerValue];
    num++;
    
    
    UIView *superView = containerView.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSDictionary *comDic = _beidouGroupList[indexPath.section][indexPath.row][@"commodity"];
    NSString *repertory = comDic[@"num"];
    NSInteger repertoryNum = [repertory integerValue];
    if (num > repertoryNum || repertoryNum == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Number is greater than the stock", nil) withOffsetY:-50];
    } else {
        textField.text = [NSString stringWithFormat:@"%lu",(unsigned long)num];
        if (num >= 1) {
            button.enabled = YES;
        }
        [self cartEdit:sender];
    }
}



// 全选按钮
- (IBAction)allSelectButtonPressed:(UIButton *)sender {
    if (![[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"yes"] && !deleteMode) {
        if (_hasConveniency == YES) {// 不在指定地区,选择了便民商品
            [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can only be purchased in the designated area", nil) withOffsetY:0.0];
            return;
        }
    }
    
    if ((_hasConveniency == YES && _noConveniencyCount == 0) ||
        (_hasConveniency == NO && _noConveniencyCount > 0) ||
        deleteMode == YES) {// 全为便民或全为非便民或在删除模式
        sender.selected = !sender.selected;
        _bottomImageView.image = sender.selected ? [UIImage imageNamed:@"beidou_gou"] : [UIImage imageNamed:@"beidou_gou2"];
        NSString *select = sender.selected ? @"yes" : @"no";
        for (NSArray *innerList in _beidouGroupList) {
            for (NSDictionary *comDic in innerList) {
                [comDic setValue:select forKeyPath:@"wyselected"];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        [self calculateTotalPrice];
    } else {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"convenience good can’t be selected with other goods at the same time", nil) withOffsetY:0.0];
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {// 确定
        UIView *container = _selectTextField.superview;
        UIView *superView = container.superview;
        while (![superView isKindOfClass:[UITableViewCell class]]) {
            superView = superView.superview;
        }
        UITableViewCell *cell = (UITableViewCell *)superView;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        NSDictionary *comDic = _beidouGroupList[indexPath.section][indexPath.row];
        [comDic setValue:@"yes" forKey:@"wyselected"];
        
        [self deleteGood];
    } else if (buttonIndex == 1) {// 取消
        UIView *container = _selectTextField.superview;
        UIView *superView = container.superview;
        while (![superView isKindOfClass:[UITableViewCell class]]) {
            superView = superView.superview;
        }
        UITableViewCell *cell = (UITableViewCell *)superView;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        
        NSNumber *backNum = _beidouGroupList[indexPath.section][indexPath.row][@"num"];
        _selectTextField.text = [NSString stringWithFormat:@"%@",backNum];
    }
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
